import Vue from 'vue'
import VueRouter from 'vue-router'


import Login from '@/views/login'
import Layout from '@/views/layout'
import Home from '@/views/home'

import Article from '@/views/article'
import Publish from '@/views/publish'


Vue.use(VueRouter)

// 路由配置表
const routes = [{
  path: '/login',
  name: 'login',
  component: Login
}, {
  path: '/',
  component: Layout,
  children: [{
    path: '', //path为空会默认子路由渲染
    name: 'home',
    component: Home
  }, {
    path: '/article',
    name: 'article',
    component: Article

  }, {
    path: '/publish',
    name: 'publish',
    component: Publish
  }]
}, ]

const router = new VueRouter({
  routes
})

//路由导航守卫
router.beforeEach((to, from, next) => {
  const user = JSON.parse(window.localStorage.getItem('user'))
  // 校验非登陆页面的登陆状态
  if (to.path !== '/login') {
    if (user) {
      //已登陆，允许通过
      next()
    } else {
      // 未登陆，跳转到登陆页面
      next('/login')
    }
  } else {
    next()
  }
})

export default router
